import Koa from 'koa';
import Router from 'koa-router';

import registerRouter from './router';
import { resLog, errLog } from './log';

const router = new Router();

function useMidware(app: Koa): void {
    // 捕获错误
    app.use(async (ctx, next) => {
        try {
            await next();
        } catch (err: any) {
            errLog(err);
            ctx.body = 'Server Error';
            ctx.status = err.status || 500;
        }
    });

    // 跨域
    app.use(async (ctx, next) => {
        const method = ctx.request.method;
        if (method === 'OPTIONS') {
            ctx.response.status = 200;
            ctx.response.set({
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': 'true',
                'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials',
            });
            resLog(ctx.response);
        } else {
            ctx.response.set({ 'Access-Control-Allow-Origin': '*' });
            await next();
        }
    });

    registerRouter(router, app);
    app.use(router.routes());
}

export default useMidware;
